<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>吸血鬼幸存者简化版</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        dark: '#1E293B',
                        light: '#F8FAFC',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .pixel-corners {
                clip-path: polygon(
                    0% 4px, 4px 4px, 4px 0%, calc(100% - 4px) 0%, calc(100% - 4px) 4px, 100% 4px,
                    100% calc(100% - 4px), calc(100% - 4px) calc(100% - 4px), calc(100% - 4px) 100%,
                    4px 100%, 4px calc(100% - 4px), 0% calc(100% - 4px)
                );
            }
            .game-shadow {
                box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.2);
            }
        }
    </style>
</head>
<body class="bg-dark text-light min-h-screen flex flex-col items-center justify-center p-4 font-sans">
    <div class="max-w-4xl w-full">
        <!-- 游戏标题 -->
        <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-center mb-6 text-primary drop-shadow-lg">
            吸血鬼幸存者简化版
        </h1>

        <!-- 游戏信息区域 -->
        <div class="grid grid-cols-3 gap-4 mb-4">
            <div class="bg-dark/50 backdrop-blur-sm p-3 rounded-lg game-shadow">
                <div class="flex items-center">
                    <i class="fa fa-clock-o text-secondary mr-2"></i>
                    <span class="font-bold">时间:</span>
                    <span id="game-time" class="ml-2">00:00</span>
                </div>
            </div>
            <div class="bg-dark/50 backdrop-blur-sm p-3 rounded-lg game-shadow">
                <div class="flex items-center">
                    <i class="fa fa-trophy text-yellow-400 mr-2"></i>
                    <span class="font-bold">等级:</span>
                    <span id="player-level" class="ml-2">1</span>
                </div>
            </div>
            <div class="bg-dark/50 backdrop-blur-sm p-3 rounded-lg game-shadow">
                <div class="flex items-center">
                    <i class="fa fa-bolt text-primary mr-2"></i>
                    <span class="font-bold">分数:</span>
                    <span id="player-score" class="ml-2">0</span>
                </div>
            </div>
        </div>

        <!-- 游戏画布 -->
        <div class="relative">
            <canvas id="gameCanvas" class="w-full bg-dark pixel-corners game-shadow"></canvas>
            
            <!-- 游戏开始界面 -->
            <div id="startScreen" class="absolute inset-0 bg-dark/80 backdrop-blur-sm flex flex-col items-center justify-center">
                <h2 class="text-3xl font-bold text-primary mb-6">准备开始!</h2>
                <p class="text-lg mb-8 text-center px-6">使用WASD或方向键移动角色，存活尽可能长的时间!</p>
                <button id="startButton" class="bg-primary hover:bg-primary/80 text-white font-bold py-3 px-8 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-primary/50">
                    开始游戏
                </button>
            </div>

            <!-- 游戏暂停界面 -->
            <div id="pauseScreen" class="absolute inset-0 bg-dark/80 backdrop-blur-sm flex flex-col items-center justify-center hidden">
                <h2 class="text-3xl font-bold text-primary mb-6">游戏暂停</h2>
                <button id="resumeButton" class="bg-primary hover:bg-primary/80 text-white font-bold py-3 px-8 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-primary/50 mb-4">
                    继续游戏
                </button>
                <button id="restartButton" class="bg-danger hover:bg-danger/80 text-white font-bold py-3 px-8 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-danger/50">
                    重新开始
                </button>
            </div>

            <!-- 游戏结束界面 -->
            <div id="gameOverScreen" class="absolute inset-0 bg-dark/80 backdrop-blur-sm flex flex-col items-center justify-center hidden">
                <h2 class="text-3xl font-bold text-danger mb-4">游戏结束</h2>
                <p class="text-xl mb-2">你的分数: <span id="finalScore" class="font-bold">0</span></p>
                <p class="text-xl mb-6">你存活了: <span id="finalTime" class="font-bold">00:00</span></p>
                <button id="playAgainButton" class="bg-primary hover:bg-primary/80 text-white font-bold py-3 px-8 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-primary/50">
                    再玩一次
                </button>
            </div>

            <!-- 升级界面 -->
            <div id="levelUpScreen" class="absolute inset-0 bg-dark/80 backdrop-blur-sm flex flex-col items-center justify-center hidden">
                <h2 class="text-3xl font-bold text-secondary mb-6">升级!</h2>
                <div id="upgradesContainer" class="grid grid-cols-1 md:grid-cols-2 gap-4 w-full max-w-md mb-8 px-4">
                    <!-- 升级选项将通过JavaScript动态生成 -->
                </div>
                <div class="w-full max-w-md px-4">
                    <p id="upgradeDescription" class="text-center text-gray-300 mb-6"></p>
                </div>
            </div>
        </div>

        <!-- 游戏控制和信息 -->
        <div class="mt-4 grid grid-cols-2 gap-4">
            <div class="bg-dark/50 backdrop-blur-sm p-3 rounded-lg game-shadow">
                <h3 class="font-bold text-primary mb-2">控制</h3>
                <ul class="text-sm space-y-1">
                    <li><i class="fa fa-keyboard-o mr-2"></i>WASD/方向键 - 移动角色</li>
                    <li><i class="fa fa-pause mr-2"></i>P - 暂停游戏</li>
                    <li><i class="fa fa-mouse-pointer mr-2"></i>鼠标点击 - 选择升级</li>
                </ul>
            </div>
            <div class="bg-dark/50 backdrop-blur-sm p-3 rounded-lg game-shadow">
                <h3 class="font-bold text-primary mb-2">目标</h3>
                <p class="text-sm">存活尽可能长的时间，消灭敌人获得经验值升级。每次升级可以选择一种武器或属性提升。小心不要被敌人碰到!</p>
            </div>
        </div>
    </div>

    <script>
        // 游戏主逻辑
        document.addEventListener('DOMContentLoaded', () => {
            // 获取DOM元素
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
            const startScreen = document.getElementById('startScreen');
            const pauseScreen = document.getElementById('pauseScreen');
            const gameOverScreen = document.getElementById('gameOverScreen');
            const levelUpScreen = document.getElementById('levelUpScreen');
            const upgradesContainer = document.getElementById('upgradesContainer');
            const upgradeDescription = document.getElementById('upgradeDescription');
            const startButton = document.getElementById('startButton');
            const resumeButton = document.getElementById('resumeButton');
            const restartButton = document.getElementById('restartButton');
            const playAgainButton = document.getElementById('playAgainButton');
            const gameTimeElement = document.getElementById('game-time');
            const playerLevelElement = document.getElementById('player-level');
            const playerScoreElement = document.getElementById('player-score');
            const finalScoreElement = document.getElementById('finalScore');
            const finalTimeElement = document.getElementById('finalTime');

            // 设置画布尺寸
            canvas.width = 800;
            canvas.height = 600;

            // 游戏状态
            let gameRunning = false;
            let gamePaused = false;
            let gameOver = false;
            let showLevelUp = false;
            let score = 0;
            let level = 1;
            let experience = 0;
            let experienceToNextLevel = 100;
            let gameTime = 0;
            let lastTimestamp = 0;
            let gameLoopId = null;

            // 游戏配置
            const config = {
                playerSpeed: 5,
                projectileSpeed: 8,
                projectileDamage: 1,
                projectileCooldown: 200,
                enemySpawnRate: 1000,
                enemyMinSpeed: 1,
                enemyMaxSpeed: 3,
                enemyMinHealth: 1,
                enemyMaxHealth: 3,
                enemyValue: 10,
                levelExperienceMultiplier: 1.5,
                upgradeCooldown: 5000, // 升级冷却时间（毫秒）
            };

            // 玩家
            const player = {
                x: canvas.width / 2,
                y: canvas.height / 2,
                radius: 15,
                speed: config.playerSpeed,
                color: '#3B82F6',
                health: 100,
                maxHealth: 100,
                invulnerable: false,
                lastShot: 0,
                projectiles: [],
                weapons: [
                    {
                        type: 'basic',
                        level: 1,
                        damage: config.projectileDamage,
                        cooldown: config.projectileCooldown,
                        lastShot: 0,
                        color: '#3B82F6',
                        upgradeDescription: '增加基础射击的伤害和射速'
                    }
                ],
                activeUpgrades: [],
                moveUp: false,
                moveDown: false,
                moveLeft: false,
                moveRight: false
            };

            // 敌人
            let enemies = [];

            // 升级选项
            const upgradeOptions = [
                {
                    name: '基础射击升级',
                    description: '增加基础射击的伤害和射速',
                    apply: () => {
                        const weapon = player.weapons.find(w => w.type === 'basic');
                        if (weapon) {
                            weapon.level++;
                            weapon.damage += 1;
                            weapon.cooldown = Math.max(50, weapon.cooldown - 30);
                        }
                    }
                },
                {
                    name: '移动速度提升',
                    description: '增加角色的移动速度',
                    apply: () => {
                        player.speed += 0.5;
                    }
                },
                {
                    name: '生命值提升',
                    description: '增加最大生命值并恢复当前生命值',
                    apply: () => {
                        player.maxHealth += 20;
                        player.health = player.maxHealth;
                    }
                },
                {
                    name: '新武器: 爆炸射击',
                    description: '解锁爆炸射击武器，对范围内敌人造成伤害',
                    apply: () => {
                        if (!player.weapons.some(w => w.type === 'explosion')) {
                            player.weapons.push({
                                type: 'explosion',
                                level: 1,
                                damage: 5,
                                cooldown: 2000,
                                lastShot: 0,
                                color: '#EF4444',
                                upgradeDescription: '增加爆炸射击的伤害和范围'
                            });
                        }
                    }
                },
                {
                    name: '攻击范围提升',
                    description: '增加所有武器的攻击范围',
                    apply: () => {
                        player.weapons.forEach(weapon => {
                            if (weapon.type === 'basic') {
                                // 对于基础武器，增加子弹的射程
                                player.activeUpgrades.push('basicRange');
                            } else if (weapon.type === 'explosion') {
                                // 对于爆炸武器，增加爆炸半径
                                player.activeUpgrades.push('explosionRange');
                            }
                        });
                    }
                },
                {
                    name: '自动射击',
                    description: '角色可以向四周自动射击',
                    apply: () => {
                        player.activeUpgrades.push('autoFire');
                    }
                }
            ];

            // 键盘控制
            document.addEventListener('keydown', (e) => {
                if (gameRunning && !gameOver && !showLevelUp) {
                    switch(e.key) {
                        case 'w':
                        case 'W':
                        case 'ArrowUp':
                            player.moveUp = true;
                            break;
                        case 's':
                        case 'S':
                        case 'ArrowDown':
                            player.moveDown = true;
                            break;
                        case 'a':
                        case 'A':
                        case 'ArrowLeft':
                            player.moveLeft = true;
                            break;
                        case 'd':
                        case 'D':
                        case 'ArrowRight':
                            player.moveRight = true;
                            break;
                        case 'p':
                        case 'P':
                            togglePause();
                            break;
                    }
                }
            });

            document.addEventListener('keyup', (e) => {
                switch(e.key) {
                    case 'w':
                    case 'W':
                    case 'ArrowUp':
                        player.moveUp = false;
                        break;
                    case 's':
                    case 'S':
                    case 'ArrowDown':
                        player.moveDown = false;
                        break;
                    case 'a':
                    case 'A':
                    case 'ArrowLeft':
                        player.moveLeft = false;
                        break;
                    case 'd':
                    case 'D':
                    case 'ArrowRight':
                        player.moveRight = false;
                        break;
                }
            });

            // 鼠标控制（选择升级）
            document.addEventListener('click', (e) => {
                if (showLevelUp) {
                    const upgradeButton = e.target.closest('.upgrade-option');
                    if (upgradeButton) {
                        const upgradeIndex = parseInt(upgradeButton.dataset.index);
                        applyUpgrade(upgradeIndex);
                        hideLevelUpScreen();
                    }
                }
            });

            // 按钮事件
            startButton.addEventListener('click', startGame);
            resumeButton.addEventListener('click', togglePause);
            restartButton.addEventListener('click', restartGame);
            playAgainButton.addEventListener('click', restartGame);

            // 开始游戏
            function startGame() {
                startScreen.classList.add('hidden');
                gameRunning = true;
                gamePaused = false;
                gameOver = false;
                score = 0;
                level = 1;
                experience = 0;
                experienceToNextLevel = 100;
                gameTime = 0;
                
                // 重置玩家
                player.x = canvas.width / 2;
                player.y = canvas.height / 2;
                player.health = player.maxHealth;
                player.speed = config.playerSpeed;
                player.weapons = [
                    {
                        type: 'basic',
                        level: 1,
                        damage: config.projectileDamage,
                        cooldown: config.projectileCooldown,
                        lastShot: 0,
                        color: '#3B82F6',
                        upgradeDescription: '增加基础射击的伤害和射速'
                    }
                ];
                player.activeUpgrades = [];
                
                // 清空敌人和子弹
                enemies = [];
                player.projectiles = [];
                
                // 更新UI
                updateGameUI();
                
                // 开始游戏循环
                lastTimestamp = performance.now();
                gameLoopId = requestAnimationFrame(gameLoop);
                
                // 开始生成敌人
                spawnEnemy();
            }

            // 暂停/继续游戏
            function togglePause() {
                if (gameOver) return;
                
                gamePaused = !gamePaused;
                
                if (gamePaused) {
                    pauseScreen.classList.remove('hidden');
                    cancelAnimationFrame(gameLoopId);
                } else {
                    pauseScreen.classList.add('hidden');
                    lastTimestamp = performance.now();
                    gameLoopId = requestAnimationFrame(gameLoop);
                }
            }

            // 游戏结束
            function endGame() {
                gameRunning = false;
                gameOver = true;
                cancelAnimationFrame(gameLoopId);
                
                // 更新UI
                finalScoreElement.textContent = score;
                finalTimeElement.textContent = formatTime(gameTime);
                gameOverScreen.classList.remove('hidden');
            }

            // 重新开始游戏
            function restartGame() {
                gameOverScreen.classList.add('hidden');
                pauseScreen.classList.add('hidden');
                startGame();
            }

            // 显示升级界面
            function showLevelUpScreen() {
                showLevelUp = true;
                cancelAnimationFrame(gameLoopId);
                
                // 随机选择3个升级选项
                const shuffledUpgrades = [...upgradeOptions].sort(() => 0.5 - Math.random());
                const selectedUpgrades = shuffledUpgrades.slice(0, 3);
                
                // 清空升级容器
                upgradesContainer.innerHTML = '';
                
                // 添加升级选项
                selectedUpgrades.forEach((upgrade, index) => {
                    const upgradeElement = document.createElement('div');
                    upgradeElement.className = 'upgrade-option bg-dark/70 hover:bg-dark/90 border border-gray-700 rounded-lg p-4 cursor-pointer transition-all duration-300 transform hover:scale-105';
                    upgradeElement.dataset.index = index;
                    
                    upgradeElement.innerHTML = `
                        <h3 class="font-bold text-secondary mb-2">${upgrade.name}</h3>
                        <p class="text-sm text-gray-300">${upgrade.description}</p>
                    `;
                    
                    upgradeElement.addEventListener('mouseenter', () => {
                        upgradeDescription.textContent = upgrade.description;
                    });
                    
                    upgradesContainer.appendChild(upgradeElement);
                });
                
                // 显示升级界面
                levelUpScreen.classList.remove('hidden');
            }

            // 隐藏升级界面
            function hideLevelUpScreen() {
                showLevelUp = false;
                levelUpScreen.classList.add('hidden');
                lastTimestamp = performance.now();
                gameLoopId = requestAnimationFrame(gameLoop);
            }

            // 应用升级
            function applyUpgrade(index) {
                const shuffledUpgrades = [...upgradeOptions].sort(() => 0.5 - Math.random());
                const selectedUpgrade = shuffledUpgrades[index];
                
                // 应用升级
                selectedUpgrade.apply();
                
                // 更新经验值
                experience = 0;
                experienceToNextLevel = 100 * (level ** config.levelExperienceMultiplier);
                
                // 更新UI
                updateGameUI();
            }

            // 生成敌人
            function spawnEnemy() {
                if (!gameRunning || gamePaused || gameOver || showLevelUp) return;
                
                // 随机位置（屏幕边缘）
                let x, y;
                const side = Math.floor(Math.random() * 4);
                
                switch(side) {
                    case 0: // 上边
                        x = Math.random() * canvas.width;
                        y = -30;
                        break;
                    case 1: // 右边
                        x = canvas.width + 30;
                        y = Math.random() * canvas.height;
                        break;
                    case 2: // 下边
                        x = Math.random() * canvas.width;
                        y = canvas.height + 30;
                        break;
                    case 3: // 左边
                        x = -30;
                        y = Math.random() * canvas.height;
                        break;
                }
                
                // 随机属性
                const health = Math.floor(Math.random() * (config.enemyMaxHealth - config.enemyMinHealth + 1)) + config.enemyMinHealth;
                const speed = config.enemyMinSpeed + (Math.random() * (config.enemyMaxSpeed - config.enemyMinSpeed));
                const size = 10 + (health * 3);
                const color = getEnemyColor(health);
                
                // 创建敌人
                enemies.push({
                    x,
                    y,
                    radius: size,
                    speed,
                    health,
                    maxHealth: health,
                    color,
                    value: health * config.enemyValue
                });
                
                // 安排下一个敌人
                const nextSpawnTime = Math.max(300, config.enemySpawnRate - (gameTime * 5));
                setTimeout(spawnEnemy, nextSpawnTime);
            }

            // 根据敌人生命值获取颜色
            function getEnemyColor(health) {
                switch(health) {
                    case 1: return '#EF4444'; // 红色
                    case 2: return '#F59E0B'; // 橙色
                    case 3: return '#EAB308'; // 黄色
                    case 4: return '#10B981'; // 绿色
                    case 5: return '#3B82F6'; // 蓝色
                    default: return '#8B5CF6'; // 紫色
                }
            }

            // 更新游戏状态
            function update(deltaTime) {
                if (!gameRunning || gamePaused || gameOver || showLevelUp) return;
                
                // 更新游戏时间
                gameTime += deltaTime / 1000;
                
                // 移动玩家
                if (player.moveUp && player.y > player.radius) {
                    player.y -= player.speed;
                }
                if (player.moveDown && player.y < canvas.height - player.radius) {
                    player.y += player.speed;
                }
                if (player.moveLeft && player.x > player.radius) {
                    player.x -= player.speed;
                }
                if (player.moveRight && player.x < canvas.width - player.radius) {
                    player.x += player.speed;
                }
                
                // 自动射击
                if (player.activeUpgrades.includes('autoFire')) {
                    const now = performance.now();
                    const basicWeapon = player.weapons.find(w => w.type === 'basic');
                    
                    if (basicWeapon && now - basicWeapon.lastShot > basicWeapon.cooldown) {
                        // 向8个方向发射子弹
                        const directions = [
                            {dx: 0, dy: -1},  // 上
                            {dx: 1, dy: -1},  // 右上
                            {dx: 1, dy: 0},   // 右
                            {dx: 1, dy: 1},   // 右下
                            {dx: 0, dy: 1},   // 下
                            {dx: -1, dy: 1},  // 左下
                            {dx: -1, dy: 0},  // 左
                            {dx: -1, dy: -1}  // 左上
                        ];
                        
                        directions.forEach(dir => {
                            player.projectiles.push({
                                x: player.x,
                                y: player.y,
                                radius: 5,
                                speed: config.projectileSpeed,
                                damage: basicWeapon.damage,
                                dx: dir.dx,
                                dy: dir.dy,
                                color: basicWeapon.color,
                                range: player.activeUpgrades.includes('basicRange') ? 300 : 200,
                                distance: 0
                            });
                        });
                        
                        basicWeapon.lastShot = now;
                    }
                }
                
                // 更新子弹
                player.projectiles.forEach(projectile => {
                    // 移动子弹
                    projectile.x += projectile.dx * projectile.speed;
                    projectile.y += projectile.dy * projectile.speed;
                    projectile.distance += projectile.speed;
                    
                    // 检查是否超出射程
                    if (projectile.distance > projectile.range) {
                        projectile.toRemove = true;
                        
                        // 爆炸子弹
                        if (projectile.type === 'explosion') {
                            createExplosion(projectile.x, projectile.y, projectile.damage);
                        }
                    }
                });
                
                // 移除超出射程的子弹
                player.projectiles = player.projectiles.filter(projectile => !projectile.toRemove);
                
                // 更新敌人
                enemies.forEach(enemy => {
                    // 向玩家移动
                    const dx = player.x - enemy.x;
                    const dy = player.y - enemy.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    if (distance > 0) {
                        enemy.x += (dx / distance) * enemy.speed;
                        enemy.y += (dy / distance) * enemy.speed;
                    }
                    
                    // 检查与玩家的碰撞
                    if (!player.invulnerable && distance < player.radius + enemy.radius) {
                        // 玩家受伤
                        player.health -= 10;
                        player.invulnerable = true;
                        
                        // 短暂闪烁效果
                        setTimeout(() => {
                            player.invulnerable = false;
                        }, 1000);
                        
                        // 检查游戏结束
                        if (player.health <= 0) {
                            endGame();
                        }
                    }
                });
                
                // 检测子弹与敌人的碰撞
                for (let i = player.projectiles.length - 1; i >= 0; i--) {
                    const projectile = player.projectiles[i];
                    let hitEnemy = false;
                    
                    for (let j = enemies.length - 1; j >= 0; j--) {
                        const enemy = enemies[j];
                        const dx = projectile.x - enemy.x;
                        const dy = projectile.y - enemy.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        
                        if (distance < projectile.radius + enemy.radius) {
                            // 敌人受伤
                            enemy.health -= projectile.damage;
                            
                            // 移除子弹
                            player.projectiles.splice(i, 1);
                            hitEnemy = true;
                            
                            // 检查敌人是否死亡
                            if (enemy.health <= 0) {
                                // 增加分数和经验
                                score += enemy.value;
                                experience += enemy.value / 2;
                                
                                // 移除敌人
                                enemies.splice(j, 1);
                                
                                // 检查是否升级
                                if (experience >= experienceToNextLevel) {
                                    level++;
                                    setTimeout(showLevelUpScreen, 100);
                                }
                                
                                // 更新UI
                                updateGameUI();
                            }
                            
                            break;
                        }
                    }
                    
                    if (hitEnemy) break;
                }
                
                // 定期触发特殊武器
                const now = performance.now();
                player.weapons.forEach(weapon => {
                    if (weapon.type === 'explosion' && now - weapon.lastShot > weapon.cooldown) {
                        // 创建爆炸
                        player.projectiles.push({
                            x: player.x,
                            y: player.y,
                            radius: 10,
                            speed: 0,
                            damage: weapon.damage,
                            color: weapon.color,
                            range: player.activeUpgrades.includes('explosionRange') ? 150 : 100,
                            distance: 0,
                            type: 'explosion',
                            toRemove: true // 立即移除，但会创建爆炸效果
                        });
                        
                        weapon.lastShot = now;
                    }
                });
            }

            // 创建爆炸效果
            function createExplosion(x, y, damage) {
                // 对范围内的敌人造成伤害
                const explosionRadius = player.activeUpgrades.includes('explosionRange') ? 150 : 100;
                
                enemies.forEach(enemy => {
                    const dx = x - enemy.x;
                    const dy = y - enemy.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    if (distance < explosionRadius) {
                        enemy.health -= damage;
                        
                        // 检查敌人是否死亡
                        if (enemy.health <= 0) {
                            // 增加分数和经验
                            score += enemy.value;
                            experience += enemy.value / 2;
                            
                            // 移除敌人
                            const enemyIndex = enemies.findIndex(e => e === enemy);
                            if (enemyIndex !== -1) {
                                enemies.splice(enemyIndex, 1);
                            }
                            
                            // 检查是否升级
                            if (experience >= experienceToNextLevel) {
                                level++;
                                setTimeout(showLevelUpScreen, 100);
                            }
                            
                            // 更新UI
                            updateGameUI();
                        }
                    }
                });
            }

            // 渲染游戏
            function render() {
                // 清空画布
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 绘制背景网格
                drawGrid();
                
                // 绘制玩家
                ctx.beginPath();
                ctx.arc(player.x, player.y, player.radius, 0, Math.PI * 2);
                ctx.fillStyle = player.invulnerable ? '#FFFFFF' : player.color;
                ctx.fill();
                ctx.closePath();
                
                // 绘制玩家生命值
                ctx.beginPath();
                ctx.rect(
                    player.x - player.radius, 
                    player.y - player.radius - 15, 
                    player.radius * 2, 
                    5
                );
                ctx.fillStyle = '#333';
                ctx.fill();
                ctx.closePath();
                
                ctx.beginPath();
                ctx.rect(
                    player.x - player.radius, 
                    player.y - player.radius - 15, 
                    (player.radius * 2) * (player.health / player.maxHealth), 
                    5
                );
                ctx.fillStyle = '#10B981';
                ctx.fill();
                ctx.closePath();
                
                // 绘制子弹
                player.projectiles.forEach(projectile => {
                    ctx.beginPath();
                    ctx.arc(projectile.x, projectile.y, projectile.radius, 0, Math.PI * 2);
                    ctx.fillStyle = projectile.color;
                    ctx.fill();
                    ctx.closePath();
                    
                    // 爆炸效果
                    if (projectile.type === 'explosion') {
                        ctx.beginPath();
                        ctx.arc(projectile.x, projectile.y, projectile.range, 0, Math.PI * 2);
                        ctx.strokeStyle = `${projectile.color}80`;
                        ctx.lineWidth = 3;
                        ctx.stroke();
                        ctx.closePath();
                    }
                });
                
                // 绘制敌人
                enemies.forEach(enemy => {
                    // 绘制敌人
                    ctx.beginPath();
                    ctx.arc(enemy.x, enemy.y, enemy.radius, 0, Math.PI * 2);
                    ctx.fillStyle = enemy.color;
                    ctx.fill();
                    ctx.closePath();
                    
                    // 绘制敌人生命值
                    ctx.beginPath();
                    ctx.rect(
                        enemy.x - enemy.radius, 
                        enemy.y - enemy.radius - 10, 
                        enemy.radius * 2, 
                        3
                    );
                    ctx.fillStyle = '#333';
                    ctx.fill();
                    ctx.closePath();
                    
                    ctx.beginPath();
                    ctx.rect(
                        enemy.x - enemy.radius, 
                        enemy.y - enemy.radius - 10, 
                        (enemy.radius * 2) * (enemy.health / enemy.maxHealth), 
                        3
                    );
                    ctx.fillStyle = '#EF4444';
                    ctx.fill();
                    ctx.closePath();
                });
            }

            // 绘制背景网格
            function drawGrid() {
                const gridSize = 40;
                ctx.strokeStyle = '#2D3748';
                ctx.lineWidth = 1;
                
                // 绘制垂直线
                for (let x = 0; x < canvas.width; x += gridSize) {
                    ctx.beginPath();
                    ctx.moveTo(x, 0);
                    ctx.lineTo(x, canvas.height);
                    ctx.stroke();
                    ctx.closePath();
                }
                
                // 绘制水平线
                for (let y = 0; y < canvas.height; y += gridSize) {
                    ctx.beginPath();
                    ctx.moveTo(0, y);
                    ctx.lineTo(canvas.width, y);
                    ctx.stroke();
                    ctx.closePath();
                }
            }

            // 游戏主循环
            function gameLoop(timestamp) {
                if (!lastTimestamp) lastTimestamp = timestamp;
                const deltaTime = timestamp - lastTimestamp;
                lastTimestamp = timestamp;
                
                update(deltaTime);
                render();
                
                // 更新游戏时间显示
                gameTimeElement.textContent = formatTime(gameTime);
                
                gameLoopId = requestAnimationFrame(gameLoop);
            }

            // 更新游戏UI
            function updateGameUI() {
                playerLevelElement.textContent = level;
                playerScoreElement.textContent = score;
            }

            // 格式化时间
            function formatTime(seconds) {
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = Math.floor(seconds % 60);
                return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
            }
        });
    </script>
</body>
</html>
    